<?php
namespace AdminBundle\Services;

use AdminBundle\Task\Scheduler\Job;

/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/23
 * Time: 14:30
 */
class Scheduler
{
    private $container;
    private $job;
    private $startTime;
    private $endTime;
    private $environment;

    public function __construct($container, $environment = 'dev')
    {
        $this->container = $container;
        $this->environment = $environment;

        $this->job = new Job($this->getDoctrine()->getManager(), $this->debug());
    }

    public function debug()
    {
        return in_array($this->environment, ['dev', 'test'], true);
    }

    public function __destruct()
    {
        if ($this->job)
            unset($this->job);
    }

    protected function getDoctrine()
    {
        if (!$this->container->has('doctrine')) {
            throw new \LogicException('The DoctrineBundle is not registered in your application.');
        }

        return $this->container->get('doctrine');
    }

    /**
     * 启动;获取当前所有作业
     * @return int
     */
    public function start()
    {
        $this->startTime = microtime(true);
        $jobs = $this->job->begin();
        return $jobs;
    }

    /**
     * 当前所有作业生成每个组的任务
     * @return int
     */
    public function run()
    {
        $count = $this->job->execute();
        $this->endTime = microtime(true);
        return $count;
    }

    /**
     * 发布新生成的数据到REDIS
     * @return array
     */
    public function publish()
    {
        $config = $this->container->getParameter('redis');
        $cache = CacheTask::getInstance($config);
        $count = $cache->taskPublish($this->getDoctrine(), ['ctime' => date('Y-m-d H:i:s', $this->startTime)]);
        $cache->destroyRedis();

        return $count;
    }

    public function nextScheduler()
    {
        $duration = round(($this->endTime - $this->startTime), 3) + 120;
        $count = $this->job->nextSchedule($duration);
        return $count;
    }
}